package com.xyz.jucTest;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 资源类
 */
class AirConditionerLock{
    private int number=0;
    private Lock lock=new ReentrantLock();
    private Condition condition=lock.newCondition();

    public  void increment(){
        lock.lock();
        try {
            //判断
            while (number != 0){
                try {
                    //this.wait();
                    condition.await();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            //干活
            number++;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //通知
            //this.notifyAll();
            condition.signalAll();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public synchronized void decrement(){
        lock.lock();
        try {
            //判断
            while (number == 0){
                try {
                    //this.wait();
                    condition.await();
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            //干活
            number--;
            System.out.println(Thread.currentThread().getName()+"\t"+number);
            //通知
            //this.notifyAll();
            condition.signalAll();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

/**
 * @author 肖咉卓
 *
 * Lock 方法实现
 *
 * 题目：现在两个线程，可以操作初始值为零的一个变量，
 * 实现一个线程对该变量加1，一个线程对该变量减1，
 * 实现交替，来10轮，变量初始值为零
 *
 * 1   高聚低合前提下，线程操作资源类
 *多线程横向调度机制
 * 2  判断/干活/通知
 * 3  多线程交互中，必须要防止多线程的虚假唤醒,也即（必须要要用 while 来判断，不能用if）
 */
public class ThreadWaitNotifyDemoLock {
    public static void main(String[] args) {
        AirConditioner airConditioner=new AirConditioner();
        new Thread(() ->{for (int i=0;i < 10;i++){airConditioner.increment();}},"A").start();
        new Thread(() ->{for (int i=0;i < 10;i++){airConditioner.decrement();}},"B").start();
        new Thread(() ->{for (int i=0;i < 10;i++){airConditioner.increment();}},"C").start();
        new Thread(() ->{for (int i=0;i < 10;i++){airConditioner.decrement();}},"D").start();
    }
}
